package com.yoke.controller.visitors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.OrderBaseControl;
import com.yoke.common.interceptor.NotLogin;
import com.yoke.service.VisitorsService;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/9/25.
 */
@Controller
@RequestMapping("visitors")
public class VisitorsLoginControl extends OrderBaseControl {

    @Resource
    private VisitorsService visitorsService;

    @RequestMapping(value = "login.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    @NotLogin
    public String login(String name) {
        return "visitors/login";
    }

    @RequestMapping(value = "loginOk", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String loginOk(String pName, String pwd, String name) {
        pName = convertFilePath(pName);
        if (StringUtil.IsEmpty(pwd, 6, 20))
            return JsonMessage.getString(400, "请输入6-20的位的密码");
        JSONArray jsonArray;
        try {
            jsonArray = visitorsService.getUserVisitorsJson(pName);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            return JsonMessage.getString(100, "服务器累了正在休息");
        }
        if (jsonArray == null)
            return JsonMessage.getString(100, "没有客户信息");


        boolean find = false;
        JSONArray list = null;
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            String name_ = jsonObject.getString("name");
            String pwd_ = jsonObject.getString("pwd");
            if (name_.equals(name) && pwd_.equals(pwd)) {
                list = jsonObject.getJSONArray("list");
                find = true;
                break;
            }
        }
        if (!find)
            return JsonMessage.getString(100, "登录失败,请检查账号信息");
        if (list == null || jsonArray.size() <= 0)
            return JsonMessage.getString(100, "没有授权对应信息");
        session.setAttribute("Visitors_User", String.format("%s@%s", pName, name));
        session.setAttribute("Visitors_User_List", list);
        return JsonMessage.getString(200, "登录成功");
    }
}
